import * as step from '@ali/flow-step-toolkit'
import process from "process";

const FLOW_JOB_TOKEN: string = 'FLOW_JOB_TOKEN'

export async function setup(dockerRepository: string) {
    step.info(`Going to execute docker setup step`)

    const serviceConnectionId = process.env["SERVICE_CONNECTION_ID"];
    if (serviceConnectionId == undefined) {
        throw new Error('missing SERVICE_CONNECTION_ID')
    }

    const flowJobToken: string | undefined =
        process.env[FLOW_JOB_TOKEN]

    if (flowJobToken == undefined) {
        throw new Error('missing FLOW_JOB_TOKEN')
    }

    const dockerCustomPersonalCertificate = await step.certificate.getDockerCustomPersonalCertificate(flowJobToken, serviceConnectionId as string);
    if (dockerCustomPersonalCertificate == undefined || dockerCustomPersonalCertificate.username == undefined) {
        throw new Error(`get dockerCustomPersonalCertificate but error: ${JSON.stringify(dockerCustomPersonalCertificate)}`)
    }

    const dockerUsername = dockerCustomPersonalCertificate.username
    const dockerPassword = dockerCustomPersonalCertificate.password


    if (dockerUsername == undefined || dockerPassword == undefined) {
        throw new Error('missing docker username or password')
    }

    step.info(`docker login -u ${dockerUsername} -p **** ${dockerRepository}`)
    const resultCode = await step.exec.call('docker', ['login', '-u', dockerUsername, '-p', dockerPassword, dockerRepository], {
        listener: {
            stdoutLine: (line: string) => {
                step.info(line)
            },
            stderrLine: (line: string) => step.info(line),
        }
    })

    if (resultCode != 0) {
        throw new Error(`docker login -u ${dockerUsername} -p **** ${dockerRepository} but error`)
    }
}